package com.loooooo.pm2024.modules.secu;


import com.loooooo.pm2024.config.RedisUtils;
import com.loooooo.pm2024.data.Result;
import com.loooooo.pm2024.web.session.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;


@Controller
@RequestMapping("/")
public class LoginController {


    @Autowired
    RedisUtils redisUtils;



    @Autowired
    LoginService loginService;


    @GetMapping(value = "/login")
    String login(HttpServletRequest request, Model model) {
        if (request.getParameter("error") != null) {
            model.addAttribute("exception", "");
        }
        return "sys/user.login";
    }

    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    Result loginAPI(@RequestBody Login login, HttpServletRequest request) {
        Result result = loginService.login(login);
        if (result.getErrorCode() == 0 && Objects.equals(Boolean.TRUE, login.getSession())) {
            HttpSession session = SessionUtils.getSession(true);
            session.setAttribute("username", LoginedUserHolder.get().getUsername());
            session.setAttribute("type", LoginedUserHolder.get().getLoginType());
            session.setAttribute("userid", LoginedUserHolder.get().getUserId());
            SessionCache.put(session);
        }
        return result;
    }

    @PostMapping(value = "/login")
    String loginAPI2(@ModelAttribute Login login, HttpServletRequest request) {
        Result result = loginService.login(login);
        if (result.getErrorCode() == 0) {
            HttpSession session = SessionUtils.getSession(true);
            session.setAttribute("username", LoginedUserHolder.get().getUsername());
            session.setAttribute("type", LoginedUserHolder.get().getLoginType());
            session.setAttribute("userid", LoginedUserHolder.get().getUserId());
            SessionCache.put(session);
            Object redirectUrl = session.getAttribute("redirectUrl");
            session.removeAttribute("redirectUrl");
            return "redirect:" + (redirectUrl == null ? "/" : redirectUrl.toString());
        }
        return "redirect:" + request.getHeader("Referer");

    }

    @RequestMapping("/logout")
    String logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = SessionUtils.getSession(false);
        if (session != null) {
            session.invalidate();
            ///UserSessionHolder.remove();
        }

        return "redirect:" + request.getHeader("Referer");
    }


}
